<template>
    <el-dialog width="600px" title="提示" :model-value="visible" @open="handleOpen" @close="closeDialog">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>页面权限</span>
                </div>
            </template>
            <el-tree ref="treeData" :data="tree" show-checkbox style="max-width: 600px;" node-key="url"></el-tree>
        </el-card>
        <el-card class="mt">
            <template #header>
                <div class="card-header">
                    <span>按钮权限</span>
                </div>
            </template>
            <el-checkbox-group v-model="initBtnAuth">
                <el-checkbox label="全部" value="all"></el-checkbox>
                <el-checkbox label="添加" value="add"></el-checkbox>
                <el-checkbox label="编辑" value="edit"></el-checkbox>
                <el-checkbox label="删除" value="delete"></el-checkbox>
            </el-checkbox-group>
        </el-card>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="$emit('close')">取消</el-button>
                <el-button type="primary" @click="updateAuth">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script lang="ts" setup>
import { defineProps, ref, defineEmits } from 'vue';
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store/auth'
import { transformMenu } from '@/utils/transformMenu'
import { updateUserAuthAPI } from '@/api/system'
const useStore = useUserStore()
const emit = defineEmits(['close','reload'])
const props = defineProps({
    visible: {
        type: Boolean,
        require: true
    },
    checkedKeys: {
        type: Array,
        require: true
    },
    BtnAuth: {
        require: true
    },
    accountNo: {
        type: String,
        require: true
    }
})
const treeData = ref()
// 全部菜单
const { menu } = storeToRefs(useStore)
// 树形的结构类型
const tree = ref(transformMenu(menu.value))
// 打开页面时自动选中当前用户的权限
const handleOpen = () => {
    treeData.value.setCheckedKeys(props.checkedKeys)
    initBtnAuth.value = props.BtnAuth
}
// 关闭弹窗
const closeDialog = () => {
    emit('close')
}

const initBtnAuth = ref<any[]>([])
const updateAuth = async () => {
    try {
        const res = await updateUserAuthAPI(props.accountNo, treeData.value.getCheckedKeys(true), initBtnAuth.value)
        if (res.code === 200) {
            ElMessage({
                message: '权限修改成功',
                type: 'success',
            })
            emit('close')
            emit('reload')
        }
    } catch (error) {

    } finally {

    }
}
</script>